package com.lottery.ruok.lottrey.activity;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.adapter.ActivieViewpagerAdapter;
import com.lottery.ruok.lottrey.eventbusObject.ActivitiesCenterActivityObj;
import com.lottery.ruok.lottrey.eventbusObject.ActivitiesCenterRefreshEvent;
import com.lottery.ruok.lottrey.eventbusObject.GoHomeEvent;
import com.lottery.ruok.lottrey.eventbusObject.LoginSuccess;
import com.lottery.ruok.lottrey.ext.GlideExt;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.ActivityListRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.JoinActivityRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.ActivityListResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.JoinActivityResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.ReceiveRewardResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import utils.Utils;

//活动详情Activity
public class ActivitiesViewpagerActivity extends BaseActivity implements  ViewPager.OnPageChangeListener{

    private static final int WAITING_TO_INITIATE = 1;
    private static final int PROCESSING = 2;
    private static final int EXPIRED = 3;
    private static final int PAUSE = 4;
    private static final int COMPLE = 102;

    @BindView(R.id.viewpager)
    ViewPager viewpager;

    @BindView(R.id.tv_last)
    TextView tvLast;

    @BindView(R.id.tv_next)
    TextView tvNext;

    @BindView(R.id.activities_title)
    TextView activitiesTitle;

    @BindView(R.id.btn_join)
    Button btnJoin;

    @BindView(R.id.tv_expired)
    TextView tvExpired;

    @BindView(R.id.title_icon)
    ImageView titleIcon;

    private List<ActivityListResponse.ListBean> mData;
    private ActivieViewpagerAdapter adapter;
    private int activitiesID;
    private int mCurrentPage;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activities_view_pager);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        Intent intent = getIntent();
        mData = (List<ActivityListResponse.ListBean>) intent.getExtras().getSerializable("data");
        mCurrentPage = intent.getExtras().getInt("position");

        activitiesID = mData.get(mCurrentPage).getId();
        initView();
        setBottomUI();
    }

    private void initView() {
        tvLast.setText("<<上个活动");
        adapter = new ActivieViewpagerAdapter(getSupportFragmentManager(), mData);
        viewpager.setAdapter(adapter);
        viewpager.addOnPageChangeListener(this);
        viewpager.setCurrentItem(mCurrentPage);
    }

    @OnClick({R.id.btn_join, R.id.tv_last, R.id.tv_next, R.id.iv_left_back,R.id.iv_right_home})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_join:
                if (UserInfo.getToken().equals("")) {
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                    overridePendingTransition(R.anim.anim_enter_from_bottom, R.anim.activity_stay);
                } else {
                    joinActivity();
                }
                break;
            case R.id.tv_last:
                if (mCurrentPage == 0) {
                    return;
                } else {
                    mCurrentPage--;
                    setBottomUI();
                }
                viewpager.setCurrentItem(mCurrentPage, false);
                break;
            case R.id.tv_next:
                if (mCurrentPage == mData.size() - 1) {
                    return;
                } else {
                    mCurrentPage++;
                    setBottomUI();
                }
                viewpager.setCurrentItem(mCurrentPage, false);
                break;
            case R.id.iv_left_back:
                finish();
                break;
            case R.id.iv_right_home:
                startActivity(new Intent(this,MainActivity.class));
                EventBus.getDefault().post(new GoHomeEvent());
                break;
        }
    }

    /**
     * 领取奖励后刷新活动
     *
     * @param receiveRewardRequest
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ReceiveRewardResponse receiveRewardRequest) {
        refreshData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 登陆成功后更改界面
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LoginSuccess data){
        refreshAllData();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        mCurrentPage = position;
        setBottomUI();
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private void setBottomUI(){
        if (mCurrentPage == 0) {
            tvLast.setVisibility(View.INVISIBLE);
        } else {
            tvLast.setVisibility(View.VISIBLE);
        }
        if (mCurrentPage == mData.size() - 1) {
            tvNext.setVisibility(View.INVISIBLE);
        } else {
            tvNext.setVisibility(View.VISIBLE);
        }

        if (mData.get(mCurrentPage).getJoined() == 0) {
            btnJoin.setVisibility(View.VISIBLE);
        } else {
            btnJoin.setVisibility(View.INVISIBLE);
        }

        switch (mData.get(mCurrentPage).getStatus()) {
            case WAITING_TO_INITIATE:
                tvExpired.setVisibility(View.INVISIBLE);
                break;
            case PROCESSING:
                tvExpired.setVisibility(View.INVISIBLE);
                break;
            case EXPIRED:
                tvExpired.setVisibility(View.VISIBLE);
                tvExpired.setTextColor(Color.parseColor("#9b9b9b"));
                tvExpired.setText("活动已过期");
                btnJoin.setVisibility(View.INVISIBLE);
                break;
            case PAUSE:
                tvExpired.setVisibility(View.VISIBLE);
                tvExpired.setText("活动已暂停");
                tvExpired.setTextColor(Color.parseColor("#c50000"));
                btnJoin.setVisibility(View.INVISIBLE);
                break;
            case COMPLE:
                tvExpired.setVisibility(View.INVISIBLE);
                break;
        }
        activitiesTitle.setText(mData.get(mCurrentPage).getName());
        // 获取是否有可以领奖
        titleIcon.setVisibility(View.GONE);
        boolean isReceive = false;
        for (ActivityListResponse.ListBean.MissionsBean missionsBean : mData.get(mCurrentPage).getMissions()) {
            if (missionsBean.getStatus() == 3) {
                isReceive = true;
            }
        }
        if (isReceive) {
            titleIcon.setBackgroundResource(R.mipmap.icon_price_enable);
            titleIcon.setVisibility(View.VISIBLE);
        } else {
            ArrayList<ActivityListResponse.ListBean.MissionsBean> missionsBeans1 = new ArrayList<>();
            ArrayList<ActivityListResponse.ListBean.MissionsBean> missionsBeans2 = mData.get(mCurrentPage).getMissions();
            for (ActivityListResponse.ListBean.MissionsBean missionsBean : missionsBeans2) {
                if (missionsBean.getStatus() == 4) {
                    missionsBeans1.add(missionsBean);
                }
            }
            if (missionsBeans1.size() == missionsBeans2.size()) {
                titleIcon.setBackgroundResource(R.mipmap.yilingwantupian);
                titleIcon.setVisibility(View.VISIBLE);
            }
        }

    }

    /**
     * 加入活动
     */
    private void joinActivity() {
        RetrofitBase.getRetrofit().create(JoinActivityRequest.class)
                .getResult(UserInfo.getToken(), mData.get(mCurrentPage).getId() + "")
                .compose(RxHelper.<JoinActivityResponse>handleResult())
                .subscribe(new RxSubscribe<JoinActivityResponse>(this) {
                    @Override
                    protected void _onNext(JoinActivityResponse joinActivityResponse) {
                        Utils.showToast("参与成功！");
                        refreshData();
                    }

                    @Override
                    protected boolean showDialog() {
                        return true;
                    }
                });
    }

    /**
     * 刷新数据
     */
    private void refreshData() {
        RetrofitBase.getRetrofit().create(ActivityListRequest.class)
                .getResult(UserInfo.getToken(), mData.get(mCurrentPage).getId() + "", null)
                .compose(RxHelper.<ActivityListResponse>handleResult())
                .subscribe(new RxSubscribe<ActivityListResponse>(this) {
                    @Override
                    protected void _onNext(ActivityListResponse activityListResponse) {
                        //向首页发送刷新事件
                        EventBus.getDefault().post(activityListResponse);
                        //向活动中心发送刷新事件请求
                        EventBus.getDefault().post(new ActivitiesCenterRefreshEvent());
                        mData.set(mCurrentPage, activityListResponse.getList().get(0));
                        adapter.notifyDataSetChanged();
                        setBottomUI();
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }
    /**
     * 刷新所有数据
     */
    private void refreshAllData() {
        RetrofitBase.getRetrofit().create(ActivityListRequest.class)
                .getResult(UserInfo.getToken(), null, null)
                .compose(RxHelper.<ActivityListResponse>handleResult())
                .subscribe(new RxSubscribe<ActivityListResponse>(this) {
                    @Override
                    protected void _onNext(ActivityListResponse activityListResponse) {
                        mData = activityListResponse.getList();
                        adapter.setData(activityListResponse.getList());
                        adapter.notifyDataSetChanged();
                        for (int i = 0; i < mData.size(); i++) {
                            if ( mData.get(i).getId() == activitiesID) {
                                mCurrentPage = i;
                            }
                        }
                        viewpager.setCurrentItem(mCurrentPage);
                        setBottomUI();
                    }

                    @Override
                    protected boolean showDialog() {
                        return true;
                    }
                });
    }
}
